<template>
    <div>
        <video ref="video" playsinline autoplay muted></video>
        <button @click="startRecording">开始录制</button>
        <button @click="stopRecording" :disabled="!isRecording">停止录制</button>
    </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onUnmounted } from 'vue'

export default defineComponent({
    setup() {
        const video = ref<HTMLVideoElement | null>(null)
        const mediaRecorder = ref<MediaRecorder | null>(null)
        const isRecording = ref(false)
        const recordedChunks: BlobPart[] = []

        onMounted(() => {
            navigator.mediaDevices
                .getUserMedia({ video: true })
                .then((stream) => {
                    if (video.value) {
                        video.value.srcObject = stream
                    }
                    mediaRecorder.value = new MediaRecorder(stream)
                    mediaRecorder.value.ondataavailable = (event) => {
                        if (event.data.size > 0) {
                            recordedChunks.push(event.data)
                        }
                    }
                })
                .catch((error) => console.error('getUserMedia error:', error))
        })

        onUnmounted(() => {
            if (video.value && video.value.srcObject) {
                ;(video.value.srcObject as MediaStream).getTracks().forEach((track) => track.stop())
                video.value.srcObject = null
            }
        })

        const startRecording = () => {
            if (mediaRecorder.value && mediaRecorder.value.state === 'inactive') {
                mediaRecorder.value.start()
                isRecording.value = true
            }
        }

        const stopRecording = () => {
            if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
                mediaRecorder.value.stop()
                isRecording.value = false
                mediaRecorder.value.onstop = () => {
                    const blob = new Blob(recordedChunks, { type: 'video/mp4' })
                    uploadVideo(blob)
                    recordedChunks.length = 0 // 清空数组
                }
            }
        }

        const uploadVideo = (blob: Blob) => {
            const formData = new FormData()
            formData.append('video', blob, 'video.mp4')

            fetch('/api/upload', { method: 'POST', body: formData })
                .then((response) => response.json())
                .then((data) => console.log('Video uploaded successfully', data))
                .catch((error) => console.error('Upload error:', error))
        }

        return { video, startRecording, stopRecording, isRecording }
    },
})
</script>
